import path from 'node:path'
import { fileURLToPath } from 'node:url'
import { createRequire } from 'node:module'
import json from '@rollup/plugin-json'
import { nodeResolve } from '@rollup/plugin-node-resolve'
import typescript from '@rollup/plugin-typescript'


const __dirname = fileURLToPath(new URL('.', import.meta.url)) // 获取当前文件的路径
const require = createRequire(import.meta.url)

// 根据
const packagesDir = path.resolve(__dirname, 'packages')
const packageDir = path.resolve(packagesDir, process.env.TARGET) // 找到要打包的某个包


// 永远针对的是某个模块
const resolve = (p) => path.resolve(packageDir, p) // 处理路径的函数

const pkg = require(resolve('package.json'))
const name = path.basename(packageDir)

const outputConfig = {
  'esm-bundler': {
    file: resolve(`dist/${name}.esm-bundler.js`),
    format: 'es'
  },
  'cjs': {
    file: resolve(`dist/${name}.cjs.js`),
    format: 'cjs'
  },
  'global': {
    file: resolve(`dist/${name}.global.js`),
    format: 'iife',
  },
}

const buildOptions = pkg.buildOptions  // 读取 package.json 中的 buildOptions

function createConfig(format, output) {

  return {
    input: resolve('src/index.ts'),
    output: {
      ...output,
      name: buildOptions.name,
      // sourcemap: true,
    },
    plugins: [
      nodeResolve(),
      json(),
      typescript({
        tsconfig: path.resolve(__dirname, 'tsconfig.json')
      }),
    ],
  }
}

export default buildOptions.formats.map(format => {
  return createConfig(format, outputConfig[format])
})
